<template>
  <el-dialog title="角色权限设置" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
    <el-tabs tab-position="top">
      <el-tab-pane label="菜单权限">
        <div class="treeMain">
          <el-tree ref="menu" node-key="menuId" :data="menu.list" :props="menu.props" show-checkbox></el-tree>
        </div>
      </el-tab-pane>
      <el-tab-pane label="数据权限">
        <el-form label-width="100px" label-position="left">
          <el-form-item label="规则类型">
            <el-select v-model="data.dataType" placeholder="请选择">
              <el-option label="全部可见" value="1"></el-option>
              <el-option label="本人可见" value="2"></el-option>
              <el-option label="所在部门可见" value="3"></el-option>
              <el-option label="所在部门及子级可见" value="4"></el-option>
              <el-option label="选择的部门可见" value="5"></el-option>
              <el-option label="自定义" value="6"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择部门" v-show="data.dataType == '5'">
            <div class="treeMain" style="width: 100%">
              <el-tree ref="dept" node-key="departmentId" :data="data.list" :props="data.props" show-checkbox></el-tree>
            </div>
          </el-form-item>
          <el-form-item label="规则值" v-show="data.dataType == '6'">
            <el-input v-model="data.rule" clearable type="textarea" :rows="6" placeholder="请输入自定义规则代码"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="控制台模块">
        <div class="treeMain">
          <el-tree ref="grid" node-key="key" :data="grid.list" :props="grid.props" :default-checked-keys="grid.checked" show-checkbox></el-tree>
        </div>
      </el-tab-pane>
      <el-tab-pane label="控制台">
        <el-form label-width="100px" label-position="left">
          <el-form-item label="控制台视图">
            <el-select v-model="dashboard" placeholder="请选择">
              <el-option v-for="item in dashboardOptions" :key="item.value" :label="item.label" :value="item.value">
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 12px">{{ item.views }}</span>
              </el-option>
            </el-select>
            <div class="el-form-item-msg">用于控制角色登录后控制台的视图</div>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script>
export default {
  emits: ['success', 'closed'],
  data() {
    return {
      roleIds: '',
      visible: false,
      isSaveing: false,
      menu: {
        list: [],
        checked: [],
        props: {
          label: data => {
            return data.meta.title;
          },
        },
      },
      grid: {
        list: [],
        checked: ['welcome', 'ver', 'time', 'progress', 'echarts', 'about'],
        props: {
          label: data => {
            return data.title;
          },
          disabled: data => {
            return data.isFixed;
          },
        },
      },
      data: {
        dataType: '1',
        list: [],
        checked: [],
        props: {
          label: data => {
            return data.departName;
          },
          disabled: 'disabled1',
        },
        rule: '',
      },
      dashboard: '0',
      dashboardOptions: [
        {
          value: '0',
          label: '数据统计',
          views: 'stats',
        },
        {
          value: '1',
          label: '工作台',
          views: 'work',
        },
      ],
    };
  },
  mounted() {
    // this.getMenu();
    // this.getDept();
    this.getGrid();
  },
  methods: {
    async open(roleIds) {
      this.visible = true;
      this.roleIds = roleIds;
      await this.getMenu();
      await this.getDept();
      this.getRoleDetail();
    },
    async submit() {
      this.isSaveing = true;

      //选中的和半选的合并后传值接口

      //菜单
      var checkedKeys = this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys());

      var menus = [];
      if (checkedKeys != null && checkedKeys.length > 0) {
        for (var i = 0; i < checkedKeys.length; i++) {
          menus.push({ menuId: checkedKeys[i] });
        }
      }
      var permission = [];
      //部门（数据权限）
      var dataType = this.data.dataType;

      var checkedKeys_dept = this.$refs.dept.getCheckedKeys().concat(this.$refs.dept.getHalfCheckedKeys());

      var deptIds = '';
      if (checkedKeys_dept != null && checkedKeys_dept.length > 0) {
        for (var di = 0; di < checkedKeys_dept.length; di++) {
          deptIds += checkedKeys_dept[di] + ',';
        }
      }
      permission.push({
        authType: 'data',
        authKey: dataType,
        authValue: dataType == '6' ? this.data.rule : deptIds.slice(0, deptIds.length - 1),
      });

      //控制台模块
      var checkedKeys_grid = this.$refs.grid.getCheckedKeys().concat(this.$refs.grid.getHalfCheckedKeys());

      var gridIds = '';
      if (checkedKeys_grid != null && checkedKeys_grid.length > 0) {
        for (var gi = 0; gi < checkedKeys_grid.length; gi++) {
          gridIds += checkedKeys_grid[gi] + ',';
        }
      }

      permission.push({
        authType: 'dashboardmodule',
        authKey: '',
        authValue: gridIds.slice(0, gridIds.length - 1),
      });
      //控制台
      var checkdashboard = this.dashboard;

      permission.push({
        authType: 'dashboard',
        authKey: '',
        authValue: checkdashboard,
      });
      if (this.roleIds != null && this.roleIds.length > 0) {
        for (let index = 0; index < this.roleIds.length; index++) {
          var element = this.roleIds[index].roleId;
          var requet = {
            roleId: element,
            menus: menus,
            permissions: permission,
          };

          await this.$API.role.authSet.post(requet);
        }
      }

      setTimeout(() => {
        this.isSaveing = false;
        this.visible = false;
        this.$message.success('操作成功');
        this.$emit('success');
      }, 1000);
    },
    async getMenu() {
      var res = await this.$API.system.menu.list.get();
      this.menu.list = res.data;
    },
    checkedMenu() {
      this.$nextTick(() => {
        let filterKeys = this.menu.checked.filter(key => {
          var t = this.$refs.menu.getNode(key);

          if (t == null) return false;
          return t.isLeaf;
        });
        this.$refs.menu.setCheckedKeys(filterKeys, true);
      });
    },
    async getDept() {
      var res = await this.$API.department.avaliableTree.get();
      this.data.list = res.data;
      // this.data.checked = []; //"12", "2", "21", "22", "1"
    },
    checkedDept() {
      this.$nextTick(() => {
        let filterKeys = this.data.checked.filter(key => {
          var t = this.$refs.dept.getNode(key);

          if (t == null) return false;

          return t.isLeaf;
        });
        this.$refs.dept.setCheckedKeys(filterKeys, true);
      });
    },
    getGrid() {
      this.grid.list = [
        {
          key: 'welcome',
          title: '欢迎',
          isFixed: true,
        },
        {
          key: 'ver',
          title: '版本信息',
          isFixed: true,
        },
        {
          key: 'time',
          title: '时钟',
        },
        {
          key: 'progress',
          title: '进度环',
        },
        {
          key: 'echarts',
          title: '实时收入',
        },
        {
          key: 'about',
          title: '关于项目',
        },
      ];
    },

    async getRoleDetail() {
      this.$nextTick(async () => {
        var data = await this.$API.role.detail.get(this.roleIds[0].roleId);

        if (data.data != null && data.data.menus != null) {
          for (let index = 0; index < data.data.menus.length; index++) {
            const element = data.data.menus[index];
            this.menu.checked.push(element.menuId);
          }
        }

        if (data.data != null && data.data.permissions != null) {
          for (let index = 0; index < data.data.permissions.length; index++) {
            const element = data.data.permissions[index];

            if (element.authType == 'data') {
              if (element.authValue != null && element.authValue != undefined) {
                this.data.checked = element.authValue.split(',');
              } else {
                this.data.rule = element.authValue;
              }
              this.data.dataType = element.authKey;
            } else if (element.authType == 'dashboardmodule') {
              this.grid.checked = element.authValue.split(',');
            } else if (element.authType == 'dashboard') {
              this.dashboard = element.authValue;
            }
          }
        }

        this.checkedMenu();
        this.checkedDept();
      });
    },
  },
};
</script>

<style scoped>
.treeMain {
  height: 280px;
  overflow: auto;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
}
</style>
